<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <!--      :titleName="$route.query.type === 'CheckResult' ? '结果审批': '返样审批'"-->
      <modules-title :titleName="auditData.Flow.Name">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="small" @click="handleBack">返回
          </el-button>
          <el-button type="primary" size="small"
                     v-if="$route.query.type === 'CheckResult'"
                     @click="handlReport(form.id)">查看报告
          </el-button>
          <approval :affair.sync="auditData" :is-text="false" @refresh="refreshData"
                    @submit="onSubmit" @toEdit="toEdit" @cancel="onCancel"/>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">

      <item-title title="基础数据" :borderShow="false"/>
      <taskForm :form="form" :check_num="check_num" :booleBoole="booleBoole"/>

      <item-title title="审批记录" :borderShow="false"/>
      <comment-view :datas="auditData"/>

    </div>
    <el-dialog title="结果审批" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
               :close-on-click-modal="false" v-if="open">
      <el-form ref="formOpen" :model="formOpen" :rules="rules" label-width="100px" size="small">
        <el-form-item label="审批结果">
          <el-radio-group v-model="formOpen.check_status">
            <el-radio v-for="(item,index) in buttonList" :key="index" :label="item.Type">
              {{item.Name}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input type="textarea" :rows="2" v-model="formOpen.check_advice"
                    placeholder="请输入审批意见"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          确定
        </el-button>
      </div>

    </el-dialog>
    <reportdialog ref="reportdialog" :formOpen="formOpen" :rowList="rowList"/>
  </div>
</template>

<script>
  import {
    viewQuality,
    myTaskdetail,
    reportCheck,
    viewReport,
    taskdetail,
    sampleReturnCheck, sampleListReport, sampleListTable
  } from '@/api/sampleInspection'

  export default {
    components: {
      taskForm: () => import('../modules/taskForm'),
      reportdialog: () => import('../modules/reportList.vue')
    },
    data() {
      return {
        title: '详情',
        left: 'left',
        form: {
          batch_num: null,
          batch_unit: '',
          quality_standard_type: 1,
          name: '',
          inspection_project: '',
          source: '', //来源
          experiment_goal: '', //实验目的
          inspection_goal_id: '',
          inspection_type: '', //	请验类型  1 外购物料 2 自研产品
          inspection_type_name: '',
          project_name: '', //项目名称
          project_id: '', //项目id
          project_leader_name: '',
          project_leader_id: '',
          project_phases_id: '',
          sample_info: {
            validity_date: '',
            sample_type_info: {
              same_type_id: '',
              same_type_name: ''
            },
            unit: '',
            id: '',
            name: '',
            attr: '', //规格
            cas: '', //CAS 1
            supplier: '', //供应商1
            producer: '', //生产商1
            batch_number: '', //批号1
            production_date: '', //生产日期1
            sample_type_name: '', //检品名称
            sample_type_id: '' //检品id
          },
          quality_standard_file: [], //质量文件
          sample_num: null, //送检量
          inspection_goal: '', //检验目的
          project_no: '', //项目编号
          if_reserve_sample: 1, //是否留样   1 是  2 否
          storage_conditions: '', //储存条件
          inspection_date: '', //检验日期
          quality_standard_name: '', //检验项目名称
          quality_standard_id: '', //检验项目id
          remark: '', //备注
          enclosure: [], //附件,
          project_category_id: '', //项目类别id
          project_category_name: '', //项目类别
          sign_category_id: '', //申报类别id
          sign_category_name: '', //申报类别
          synthetic_route: [],//   合成路线
          factory_inspection_report: [],// 厂检报告
          if_return_sample: 0//是否反样  0 否 1 是   int
        },
        check_num: 0,
        booleBoole: false,
        auditData: {
          Flow: {}
        },
        auditButtonName: '审批',
        isAudit: false,
        userInfo: null,
        open: false,
        rowList: {},
        formOpen: {
          tableResults: {
            id: '',
            report: [],//
            computation_sheet: [], //计算表格
            inspection_map: []//  检验图谱
          },
          relation_plan_id: ''
        },
        rules: {
          check_advice: [
            { required: true, message: '请输入审批意见', trigger: 'blur' }
          ]
        },
        openReport: false,
        fileList: [],
        fileType: undefined,
        buttonList: [],
        activeNames: ''

      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {
      calculate() {
        return function(val) {
          let str = ''
          for (let i = 0; i < val.length; i++) {
            str += val[i].name
            if (i !== val.length - 1) {
              str = str + '、'
            }
          }
          return str
        }
      }
    },
    //属性是手动定义的所需监听的值
    watch: {},
    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.detailData()
      this.userInfo = this.$store.getters.userInfo
      if (this.$route.query) {
        this.getAuditData(this.$route.query.f_id)
      }
    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //获取详情
      detailData() {
        myTaskdetail(this.$route.query.f_id).then(res => {
          if (res.code === 200) {
            this.form = res.data || {}
            console.log(this.form, '----------')
            let a = this.$route.query.f_id, b = {}
            if (res.data.return_sample_check_num) {
              this.check_num = res.data.return_sample_check_num[a]
            }
            if (
              this.form.quality_standard_file &&
              this.form.quality_standard_file.length > 0 &&
              this.form.quality_standard_id
            ) {
              viewQuality(this.form.quality_standard_id).then(res => {
                if (res.code === 200) {
                  this.form.quality_standard_file = res.data.file || []
                }
              })
            }
          }
        })
      },
      //返回
      handleBack() {
        this.$route.params.refresh = true
        this.$router.go(-1)
      },

      getAuditData(id) {
        this.$api.PROJECT_START_CHECK_DETAIL(id).then(res => {
          if (res.code === 200) {
            this.auditData = res.data
            console.log(this.auditData, '=-=------')
            this.getButton()
          }
        })
      },
      getButton() {
        if (
          this.auditData.State !== 'Done' ||
          this.auditData.State !== 'Refuse'
        ) {
          if (this.auditData.Next && this.auditData.Next.length) {
            for (let i = 0; i < this.auditData.Next.length; i++) {
              const data = this.auditData.Next[i]
              const index = data.Staffs.findIndex(
                a => a === this.userInfo.user.id
              )
              if (index !== -1) {
                this.isAudit = true
                this.auditButtonName = data.ItemName
                this.buttonList = data.Buttons || []
                let sss = this.buttonList.findIndex(a => a.Type == 'Cancel')
                if (sss !== -1) {
                  this.buttonList.splice(sss, 1)
                }
                break
              }
            }
          }
        }
      },
      // 撤销
      handlUndo() {
        const subdata = {
          flow_id: this.$route.query.f_id,
          model_type: 'CheckResult'
        }
        this.$comFun.cancelFunc(subdata).then(() => {
          this.$message({
            type: 'success',
            message: '已撤销'
          })
          this.detailData()
        }).catch(err => {
          this.$message.error(err)
        })
      },
      handlAnd() {
        this.open = true
      },
      cancel() {
        this.formOpen = {
          check_advice: '',
          check_status: 1
        }
        this.open = false
      },
      submitForm() {
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            let data = {},
              msg = ''
            data = {
              id: this.form.id,
              check_status: this.formOpen.check_status,
              check_advice: this.formOpen.check_advice
            }
            msg = '审批成功'
            reportCheck(data).then(res => {
              if (res.code === 200) {
                this.$message.success(msg)
                this.cancel()
                this.detailData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },
      async handlReport(id) {
        let row = {}
        let res = await taskdetail(id)
        if (res.code === 200) {
          row = res.data
          this.rowList = row
          this.formOpen.tableResults = {
            computation_sheet: [],
            report: [],
            inspection_map: []
          }
          if (row.computation_sheet && row.inspection_result && row.inspection_map) {
            this.formOpen.tableResults.computation_sheet = JSON.parse(JSON.stringify(row.computation_sheet)) || []
            this.formOpen.tableResults.report = JSON.parse(JSON.stringify(row.inspection_result)) || []
            this.formOpen.tableResults.inspection_map = row.inspection_map || []
            for (let i = 0; i < this.formOpen.tableResults.report.length; i++) {
              this.formOpen.tableResults.report[i].boole = true
              if (row.experiment_table_info_map) {
                this.formOpen.tableResults.report[i].ruleForm = row.experiment_table_info_map[this.formOpen.tableResults.report[i].batch_no]
              } else {
                if (row.inspection_type === 'inspection_type_wd') {
                  let ress = await sampleListTable({ id: row.relation_plan_id })
                  if (ress.code === 200) {
                    this.formOpen.tableResults.report.forEach(item => {
                      if (ress.data && ress.data[item.batch_no]) {
                        item.ruleForm = ress.data[item.batch_no]
                      }
                    })
                  }
                }
              }
            }
          }

          console.log(this.formOpen.tableResults, '-=-=-=')
          this.$refs.reportdialog.openport()
        }
      },
      refreshData() {
        this.detailData()
      },
      toEdit(affairs) {
        if (this.$route.query.type === 'CheckResult') {
          this.$message.warning('暂无此功能')
        }

        if (this.$route.query.type === 'ReturnSample') {
          this.$router.push({
            path: '/sampleInspection/taskDetails',
            query: { id: this.form.id }
          })
        }

      },
      // affairsId, stepId , type  //选择类型, template //备注, RejectStepId  //步骤id
      onSubmit(affairsId, stepId, type, template, RejectStepId, callback) {
        console.log(affairsId, stepId, type, template, RejectStepId)
        let subdata = {}, commit = undefined
        if (this.$route.query.type === 'CheckResult') {
          subdata = {
            id: this.form.id,
            check_status: type,
            check_advice: template.Remark,
            Files: template.Files
          }
          commit = reportCheck
        }
        if (this.$route.query.type === 'ReturnSample') {
          subdata = {
            id: this.form.id,
            check_status: type,
            check_advice: template.Remark,
            step_id: stepId,
            Files: template.Files
          }
          commit = sampleReturnCheck
        }

        commit(subdata).then(res => {
          if (res.code === 200) {
            this.$message.success('审批成功')
            this.cancel()
            this.detailData()
            this.getAuditData(this.$route.query.f_id)
            callback(true)
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      onCancel(affairsId, stepId, type, template, RejectStepId, callback) {
        const subdata = {
          flow_id: this.$route.query.f_id,
          model_type: this.$route.query.type
        }
        this.$comFun.cancelFunc(subdata)
          .then(() => {
            callback(true)
            this.$message({
              type: 'success',
              message: '已撤销'
            })
            this.detailData()
            this.getAuditData(this.$route.query.f_id)
            callback(true)
          })
          .catch(err => {
            this.$message.error(err)
          })
      }
    }
  }
</script>
<style scoped>
  /* @import url(); 引入css类 */
  .el-row {
    display: flex;
    justify-content: flex-start;
    flex-flow: wrap;
  }

  ::v-deep .box_card {
    border: none !important;
  }
</style>
